import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'

// 请求拦截器
http.intercept.request = (config) => {
  // 判断有token
  const app = getApp()
  if(app.token){
    config.header = {
      Authorization : `Bearer ${app.token}`,
      ...config.header
    }
  }
  return config
}

// 响应拦截器
http.intercept.response = async (res) => {
  const app = getApp()
  if(res.statusCode === 401){
    if(res.config.url.includes('/refreshToken')){
      const pages = getCurrentPages()
      const current = pages[pages.length - 1]
      wx.navigateTo({url: '/pages/login/index?redirect=' + current.route})
      return
    }
    const result = await wx.http({
      url:'/refreshToken',
      method:'POST',
      header:{ Authorization: `Bearer ${app.refreshToken}`}
    })
    const {token , refreshToken} = result.data
    app.setToken(token , refreshToken)
    return wx.http({
      ...res.config,
      header:{ Authorization: `Bearer ${app.token}`}
    })
  }
  if (res.data.code === 10000) {
    return res.data
  } else {
    return Promise.reject()
  }
}

wx.http = http

export default http
